package service

import (
	"context"
	core "ez/apps/core/document"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

func RegHost(info *ez.ServiceInfo) {
	cHost := core.NewHostCrud()
	host, _ := cHost.FindOneBy(ss.M{
		"appId":       info.Service.AppId,
		"machineCode": info.Service.MachineCode,
	}, nil)
	needToReload := false
	if host.Id == 0 {
		host.AppId = info.Service.AppId
		host.MachineCode = info.Service.MachineCode
		needToReload = true
	} else {
		if host.State == 0 {
			needToReload = true
		}
	}
	host.Weight = int64(info.Service.Weight)
	host.Ip = info.Server.ServerHost
	host.Port = int64(info.Server.ServerPort)
	host.LastTime = time.Now()
	host.State = 1
	host.StateInfo = "正常"
	e := host.Save()
	if needToReload {
		ez.DispatchToOne("HostChanged", host.Id, context.TODO())
	}
	if e != nil {
		ez.LogToConsole(e.Error())
	}
}

func HostHeartBeat(info *ez.ServiceInfo) {
	cHost := core.NewHostCrud()
	host, _ := cHost.FindOneBy(ss.M{
		"appId":       info.Service.AppId,
		"machineCode": info.Service.MachineCode,
	}, nil)
	changed := false
	if host.Id == 0 {
		host.AppId = info.Service.AppId
		host.MachineCode = info.Service.MachineCode
		changed = true
	} else {
		if host.Port != int64(info.Server.ServerPort) {
			changed = true
		}
		if host.State == 0 {
			changed = true
		}
	}
	host.Weight = int64(info.Service.Weight)
	host.Ip = info.Server.ServerHost
	host.Port = int64(info.Server.ServerPort)
	host.LastTime = time.Now()
	host.State = 1
	host.StateInfo = "正常"
	e := host.Save()
	if e != nil {
		ez.LogToConsole(e.Error())
	}
	if changed {
		ez.DispatchToOne("HostChanged", host.Id, context.TODO())
	}

}

func CheckHostAlive() {
	cHost := core.NewHostCrud()
	hosts, _ := cHost.FindBy(ss.M{
		"isOn": true,
	}, nil, 0, 0)
	for _, host := range hosts {
		if time.Now().Sub(host.LastTime).Seconds() > 10 {
			host.State = 0
			host.StateInfo = "心跳超时"
		} else {
			host.State = 1
			host.StateInfo = "正常"
			host.LastTime = time.Now()
		}
		host.Save()
	}
}
